package com.smart.bookshelf;

public class CrcUtil {


    public static String crc(String str){
        byte[] bytes = getCrc(hexStringToBytes(str));
        return bytes2HexString((bytes));
    }

    /**
     * 获取crc
     *
     * @param buf
     * @return
     */
    public static byte[] getCrc(byte[] buf) {
        byte[] crcByte = new byte[2];
        long bufLen = buf.length;
        long[] bufb = new long[(int) bufLen];
        long currentValue = 0x0000;

        for (int i = 0; i < bufLen; i++) {
            bufb[i] = buf[i] & 0xff;
            currentValue = currentValue ^ bufb[i];
            for (int j = 0; j < 8; j++) {
                if ((currentValue & 0x0001) != 0) {
                    currentValue = (currentValue >> 1) ^ 0x8408;
                } else {
                    currentValue = (currentValue >> 1);
                }
            }
        }
        crcByte[0] = (byte) ((~currentValue >> 8) & 0x00FF);
        crcByte[1] = (byte) (~currentValue & 0x00FF);
        return crcByte;
    }

    public static byte[] hexStringToBytes(String s) {
        int len = s.length();
        byte[] b = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            // 两位一组，表示一个字节,把这样表示的16进制字符串，还原成一个字节
            b[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character
                    .digit(s.charAt(i + 1), 16));
        }
        return b;
    }

    public static String bytes2HexString(byte[] b) {
        StringBuilder sbf = new StringBuilder();
        for (byte value : b) {
            String hex = Integer.toHexString(value & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sbf.append(hex.toUpperCase());
        }
        return sbf.toString().trim();
    }


}
